class PromptBuilder:
    def __init__(self, df_columns, explanations, conversation_history, user_input):
        self.df_columns = df_columns
        self.explanations = explanations
        self.conversation_history = conversation_history
        self.user_input = user_input

    def build_prompt(self):
        """构建最终的提示词，包含意图识别和代码生成的逻辑。"""
        prompt_parts = [
            self._build_conversation_history(),
            self._build_context(),
            self._build_examples(),
            self._build_explanations(),
            self._build_user_query(),
            self._build_task_instructions()
        ]
        return "\n".join(prompt_parts)

    def _build_conversation_history(self):
        """生成对话历史部分的提示词。"""
        return f"Conversation History:\n{self.conversation_history}\n"

    def _build_context(self):
        """生成数据上下文部分的提示词。"""
        return (f"The DataFrame 'df' contains the following columns: {', '.join(self.df_columns)}.\n"
                "Based on the conversation history and the following user input, determine the user's intent.")

    def _build_examples(self):
        """生成示例部分的提示词。"""
        return (
            "If the user input is a query that requires data processing or analysis, generate Python code to manipulate the DataFrame.\n"
            "If the user input is a request for a summary, explanation, or a follow-up question that does not require code execution, respond with a natural language answer.\n"
            "Ensure that if code is generated, the final result is assigned to a variable called 'result'.\n\n"
            "Examples:\n"
            
            # 示例 1: 数据查询
            "1. User Input: 'Show me the total sales for 2023.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   result = df[df['year'] == 2023]['sales'].sum()\n"
            "   ```\n\n"
            
            # 示例 2: 列解释
            "2. User Input: 'What is the meaning of the sales column?'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The sales column represents the total sales figures in dollars.'\n\n"
            
            # 示例 3: 数据摘要
            "3. User Input: 'Summarize the content of the first five rows.'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The first five rows contain information about different individuals, including their gender, age, and marriage satisfaction rating.'\n\n"
            
            # 示例 4: 表格概述
            "4. User Input: 'Give me an overview of the table above.'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The table contains demographic and marital satisfaction data, including columns such as gender, age, years married, and satisfaction rating.'\n\n"
            
            # 示例 5: 统计数据
            "5. User Input: 'Calculate the average age of individuals.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   result = df['age'].mean()\n"
            "   ```\n\n"
            
            # 示例 6: 数据过滤
            "6. User Input: 'Filter the data to show only males over 30 years old.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   result = df[(df['gender'] == 'male') & (df['age'] > 30)]\n"
            "   ```\n\n"
            
            # 示例 7: 数据解释
            "7. User Input: 'Explain the rating column.'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The rating column represents the individual's self-assessed marriage satisfaction, on a scale from 1 (least satisfied) to 5 (most satisfied).'\n\n"
            
            # 示例 8: 问题澄清
            "8. User Input: 'What does the children column signify?'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The children column indicates whether the individual has children, with possible values being \"yes\" or \"no\".'\n\n"
            
            # 示例 9: 数据总结
            "9. User Input: 'Summarize the marital satisfaction data.'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The marital satisfaction data shows a range of satisfaction levels, with most individuals rating their satisfaction between 3 and 5.'\n\n"
            
            # 示例 10: 自然语言问题
            "10. User Input: 'What can you infer about the relationship between age and marital satisfaction?' \n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'Older individuals tend to report higher levels of marital satisfaction, although this may vary based on other factors.'\n\n"
            
            # 示例 11: 数据比较
            "11. User Input: 'Compare the number of males and females in the dataset.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   result = df['gender'].value_counts()\n"
            "   ```\n\n"
            
            # 示例 12: 图表生成
            "12. User Input: 'Generate a bar chart showing the distribution of occupation ratings.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   result = df['occupation'].value_counts().plot(kind='bar')\n"
            "   plt.show()\n"
            "   ```\n\n"
            
            # 示例 13: 数据更新
            "13. User Input: 'Update the rating column by adding 1 to each value.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   df['rating'] = df['rating'] + 1\n"
            "   result = df.head()\n"
            "   ```\n\n"
            
            # 示例 14: 数据探查
            "14. User Input: 'Explore the unique values in the children column.'\n"
            "   Model Response: 'code'\n"
            "   Generated Code:\n"
            "   ```python\n"
            "   result = df['children'].unique()\n"
            "   ```\n\n"
            
            # 示例 15: 数据描述
            "15. User Input: 'Describe the education level distribution in the dataset.'\n"
            "   Model Response: 'no_code'\n"
            "   Generated Explanation: 'The education level distribution shows that most individuals have completed between 12 and 18 years of education, with a few having higher or lower levels of education.'\n"
        )



    def _build_explanations(self):
        """生成术语解释部分的提示词。"""
        explanation_text = "\nTerm Explanations:\n"
        for term, explanation in self.explanations.items():
            explanation_text += f"- {term}: {explanation}\n"
        return explanation_text

    def _build_user_query(self):
        """生成用户输入部分的提示词。"""
        return f"User Input: {self.user_input}"

    def _build_task_instructions(self):
        """生成最后的任务指令部分的提示词。"""
        return (
            "Based on the above, respond with either 'code' if Python code should be generated, or 'no_code' if a natural language response is more appropriate. "
            "If 'code', follow with the generated Python code block. If 'no_code', provide the natural language response."
        )
